#include "my_log.h"
#include "cmsis_os.h"
#include "stm32f4xx_hal.h"
#include "fatfs.h"

void test_fs(void);

void StartTaskFs(void *argument)
{
    /* USER CODE BEGIN StartTaskFs */
    my_log_init();
    log_i("Log init OK");
    
    test_fs();
    
    /* Infinite loop */
    for(;;)
    {
        log_i("Log init OK");
        osDelay(500);
        HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_0);
    }

    /* USER CODE END StartTaskFs */
}


FATFS fs;
FIL fp;
FRESULT result;
uint8_t work[512];


void test_fs(void)
{
    FRESULT result;
    
    result = f_mount(&fs, "", 1);
    
    log_i("%d, res:%d", __LINE__, result);
    
    result = f_open(&fp, "Hello.txt", FA_OPEN_ALWAYS | FA_WRITE);
    
    log_i("%d, res:%d", __LINE__, result);
    
    if(result == FR_NO_FILESYSTEM)
    {
        result = f_mkfs("", FM_FAT, 0, work, sizeof(work));
        log_i("%d, res:%d", __LINE__, result);
        
        
        if(result == FR_OK)
        {
            result = f_open(&fp, "Hello.txt", FA_OPEN_ALWAYS);
            log_i("%d, res:%d", __LINE__, result);
        }
    }
    
    uint32_t bw = 0;
    uint8_t buf[20];
    if(result == FR_OK)
    {
        result = f_write(&fp, "123456111", sizeof("123456111"), &bw);
        log_i("%d, res:%d", __LINE__, result);
        if(result != FR_OK)
        {
        }
        f_close(&fp);
    }
    
    
    result = f_open(&fp, "Hello.txt", FA_READ);
    log_i("%d, res:%d", __LINE__, result);
    
    if(result == FR_OK)
    {
        f_read(&fp, buf, 6, &bw);
        f_close(&fp);
    }
}




